//use web_sys::{Window, Document, Element, HtmlInputElement};
//use wasm_bindgen::JsCast;
use super::{Query};

pub enum Rules {
    UserName,
    //Int,
    //Uint,
    Password,
}

pub struct Validation {
    // 字段名称/规则/错误信息
    validations: Vec<(&'static str, Rules, &'static str)>,
    //errors: Vec<&'static str>,
}

impl Validation {

    /// 创建新的校验器
    pub fn new() -> Self {
        Self {
            validations: vec![],
            //errors: vec![],
        }
    }

    /// 累加校验规则到校验器当中
    pub fn add(&mut self, field: &'static str, rule: Rules, message: &'static str) -> &mut Self{
        self.validations.push((field, rule, message));
        self
    }

    /// 对每个字符进行校验
    fn validate_field(&self, field: &'static str, _rule: &Rules) -> bool {
        let input = if let Some(v) = Query::find_by_id(field) { v } else { return false; };
        let value = input.value();
        value.len() >= 5 && value.len() < 20
    }

    /// 对于全体字段进行校验
    pub fn validate(&self) -> Result<(), String> {
        let mut errors: Vec<&'static str> = vec![];
        for (field, rule, message) in &self.validations {
            if !self.validate_field(field, &rule) {
                errors.push(message);
            }
        }
        if errors.len() > 0 {
            Err(errors.join("<br />"))
        }  else {
            Ok(())
        }
    }
}


